﻿using Kingdee.BOS;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.Bill.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using LM.YF.K3Cloud.Plugin.Models;
using LM.YF.K3Cloud.Plugin.Models.Grasses;
using System;
using System.ComponentModel;
using System.Security.Cryptography;

namespace LM.YF.K3Cloud.Plugin
{
    /// <summary>
    /// 鹿奔 240413
    /// </summary>
    [Description("销售订单表单插件（获取运输路线）"), HotUpdate]
    public class SalesOrderBillPlugin : AbstractBillPlugIn
    {
        #region MyRegion

        /// <summary>
        /// 运输路线
        /// </summary>
        readonly ElementKeySchema F_RDLV_route = new ElementKeySchema
        {
            FormKey = "F_RDLV_route",
            DbKey = "F_RDLV_ROUTE",
            OrmKey = "F_RDLV_route"
        };

        /// <summary>
        /// 库存组织
        /// </summary>
        readonly ElementKeySchema FStockOrgId = new ElementKeySchema
        {
            FormKey = "FStockOrgId",
            DbKey = "FSTOCKORGID",
            OrmKey = "StockOrgId"
        };

        /// <summary>
        /// 客户
        /// </summary>
        readonly ElementKeySchema FCustId = new ElementKeySchema
        {
            FormKey = "FCustId",
            DbKey = "FCUSTID",
            OrmKey = "CustId"
        };

        /// <summary>
        /// 订单明细
        /// </summary>
        readonly ElementKeySchema FSaleOrderEntry = new ElementKeySchema
        {
            FormKey = "FSaleOrderEntry",
            DbKey = "T_SAL_ORDERENTRY",
            OrmKey = "SaleOrderEntry"
        };

        /// <summary>
        /// 销售主体
        /// </summary>
        readonly ElementKeySchema F_RDLV_saler = new ElementKeySchema
        {
            FormKey = "F_RDLV_saler",
            DbKey = "F_RDLV_SALER",
            OrmKey = "F_RDLV_saler"
        };

        #endregion

        public override void DataChanged(DataChangedEventArgs e)
        {
            base.DataChanged(e);

            if (e.Field.Key.Equals(FStockOrgId.FormKey))
            {
                GetRoute(e.Row);
            }
            else if (e.Field.Key.Equals(F_RDLV_saler.FormKey))
            {
                GetRoute(e.Row);
            }
            else if (e.Field.Key.Equals(FCustId.FormKey))
            {
                for (int i = 0, l = View.Model.GetEntryRowCount(FSaleOrderEntry.FormKey); i < l; i++)
                {
                    GetRoute(i);
                }
            }else if (e.Field.Key.Equals(F_RDLV_saler.FormKey))
            {
                for (int i = 0, l = View.Model.GetEntryRowCount(FSaleOrderEntry.FormKey); i < l; i++)
                {
                    GetRoute(i);
                }
            }
        }

        /// <summary>
        /// 获取运输路线
        /// </summary>
        private void GetRoute(int rowIndex)
        {
            var regionId = Convert.ToInt32((View.Model.GetValue(FCustId.FormKey) as DynamicObject)?["F_RDLV_Region_Id"]);
            var stockOrgId = Convert.ToInt32((View.Model.GetValue(FStockOrgId.FormKey, rowIndex) as DynamicObject)?["Id"]);
            var saleBodyId = Convert.ToInt32((View.Model.GetValue(F_RDLV_saler.FormKey) as DynamicObject)?["Id"]??"0");
            var routeData = GetRoute(Context, regionId, stockOrgId, saleBodyId);
            if (routeData.Failure == null)
            {
                View.Model.SetValue(F_RDLV_route.FormKey, routeData.RouteId, rowIndex);
                View.UpdateView(F_RDLV_route.FormKey, rowIndex);
            }
        }

        public static vzn11vmam GetRoute(Context context, int regionId, int orgId, int saleBodyId)
        {
            if (regionId == 0 || orgId == 0 || saleBodyId == 0)
            {
                return new vzn11vmam
                {
                    Failure = "参数皆为必填项"
                };
            }

            // 获取指定组织和运输区域的路线
            var routes = DBUtils.ExecuteDynamicObject(context, $@"/*dialect*/
            with 起运点 as (
	            -- 指定组织的起运点
	            select distinct FID
	            from RDLV_t_startpoint_entry
	            where F_RDLV_ORG = {orgId}
            )
            select top 1 a.FID, a.F_RDLV_CARRIER
            from RDLV_t_TransfRute as a-- 运输路线
            inner join 起运点 as b on b.FID = a.F_RDLV_START_POINT
            where 1 = 1
            -- 指定区域和销售主体
            and a.F_RDLV_DESTION = {regionId} 
            and (
                (isnull(a.F_QLTK_SALEBODY ,'0')= {saleBodyId} and {saleBodyId}=239648) or --植保
                 (isnull(F_QLTK_SALEBODY,'0')=0 and {saleBodyId}<>239648)--不等于植保的
                )
            -- 优先获取默认路线，其次优先获取最新路线
            order by a.F_RDLV_DEFAULT desc, a.FID desc;");
            if (!(routes?.Count > 0))
            {
                return new vzn11vmam
                {
                    Failure = "未查询到匹配的运输路线"
                };
            }
            var route = routes[0];
            var routeId = Convert.ToInt32(route["FID"]);
            var carrierId = Convert.ToInt32(route["F_RDLV_CARRIER"]);
            return new vzn11vmam
            {
                Failure = null,
                CarrierId = carrierId,
                RouteId = routeId
            };
        }
    }
}
